package com.cms.ojm.service.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cms.common.utils.PageUtils;
import com.cms.common.utils.Query;

import com.cms.ojm.dao.ClassesDao;
import com.cms.ojm.entity.ClassesEntity;
import com.cms.ojm.service.ClassesService;

import javax.annotation.Resource;


@Service("classesService")
public class ClassesServiceImpl extends ServiceImpl<ClassesDao, ClassesEntity> implements ClassesService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");
        QueryWrapper<ClassesEntity> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            wrapper.eq("id", key).or().like("name", key);
        }
        IPage<ClassesEntity> page = this.page(
                new Query<ClassesEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<ClassesEntity> listNoPage() {
        String classesList = stringRedisTemplate.opsForValue().get("classesList");
        RLock lock = redissonClient.getLock("classes_lock");
        if(StringUtils.isEmpty(classesList)){
            lock.lock();
            try{
                List<ClassesEntity> classesEntities = baseMapper.selectList(null);
                String s = JSON.toJSONString(classesEntities);
                stringRedisTemplate.opsForValue().set("classesList", s);
                return classesEntities;
            }catch (Exception e){
                List<ClassesEntity> classesEntities = baseMapper.selectList(null);
                String s = JSON.toJSONString(classesEntities);
                stringRedisTemplate.opsForValue().set("classesList", s);
                return classesEntities;
            }finally {
                lock.unlock();
            }
        }else{
            return JSON.parseObject(classesList, (new ArrayList<ClassesEntity>()).getClass());
        }
    }

}